package com.newland.starpos.partner.service.remote;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.newland.starpos.partner.exception.CustomException;
import com.newland.starpos.partner.http.ResponseEnum;
import com.newland.starpos.partner.utils.HttpUtils;
import com.newland.starpos.partner.utils.MD5Utils;
import com.newland.starpos.partner.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class GatewayService {
	
	@Value("${gateway.url}")
	private String gatewayUrl;
	
	@Value("${gateway.key}")
	private String key;

	//调用收单系统,解绑设备
	public String unbindDevice(String csn, String terminalNo) throws CustomException {
		JSONObject request = new JSONObject();
		request.put("type", "untidePos");
		request.put("sn", csn);
		request.put("trmNo", terminalNo);
		request.put("signValue", MD5Utils.encrypt(csn + terminalNo + key));
		String response;
		try {
			response = HttpUtils.postJsonU8(gatewayUrl + "/eprmadp1/untidePos.json",
							request.toJSONString());
		} catch (Exception e) {
			log.error("调用收单解绑设备失败,", e);
			throw new CustomException(ResponseEnum.REMOTE_CALL_ERROR);
		}
		JSONObject resp = JSON.parseObject(response);
		String code = resp.getString("retCode");
		if(StringUtils.equals(code, "000000"))
			return "SUCCESS";
		return resp.getString("retMsg");
	}

	// 姓名,身份证,银行卡实名认证
	public String readNameAuth(String bankCard, String identityCard, String identityName, String token) throws CustomException {
		JSONObject request = new JSONObject();
		request.put("stl_crp_no", identityCard);
		request.put("bnk_acnm", identityName);
		request.put("stl_oac", bankCard);
		request.put("ACCESS_TOKEN", token);
		String response;
		try {
			response = HttpUtils.postJsonU8(gatewayUrl + "/emercpartner/thrInfoChk.json",
					request.toJSONString());
		} catch (Exception e) {
			log.error("实名认证请求异常，异常信息：", e);
			throw new CustomException(ResponseEnum.REMOTE_CALL_ERROR);
		}
		JSONObject resp = JSON.parseObject(response);
		String code = resp.getString("retCode");
		if(!StringUtils.equals(code, "000000"))
			return resp.getString("repMsg");

		if(StringUtils.equals(resp.getString("resultcode"), "0000"))
			return "SUCCESS";
		return "身份信息有误或不匹配，请仔细核对!";
	}
}
